import { Image, Text, View } from '@tarojs/components';
import {
  hideLoading,
  login,
  redirectTo,
  removeStorageSync,
  showLoading,
  showToast,
  switchTab,
  useEffect,
  useRouter,
  useState
} from '@tarojs/taro';
import dayjs from 'dayjs';
import welcome_bg1 from '../../assets/page/welcome_bg1.jpg';
import welcome_bg2 from '../../assets/page/welcome_bg2.jpg';
import Layout from '../../components/Layout';
import XInput from '../../components/XInput';
import XList from '../../components/XList';
import {
  CacheCookies,
  CacheLastLoginUserName,
  CacheUserInfo,
  CacheLastLoginDate,
  CacheLastLoginPassword
} from '../../constant/cache';
import baseService from '../../utils/baseService';
import { getCache, setCache } from '../../utils/utils';
import BioCore from '../../components/BioAuth/BioCore';

const Login = () => {
  const lastLoginUserName = getCache(CacheLastLoginUserName);
  const lastLoginPassword = getCache(CacheLastLoginPassword);
  const [up, setUp] = useState({ account: lastLoginUserName });
  const [showAdLayout, setShowAdLayout] = useState(!lastLoginUserName);
  const [focus, setFocus] = useState({ un: false, pw: false });
  const [isAuth, setIsAuth] = useState(false);
  const {
    params: { ref }
  } = useRouter();

  useEffect(() => {
    const ck = getCache(CacheLastLoginDate);
    if (ck && dayjs().diff(dayjs(ck), 'minute') <= 3) {
      redirectHomePage();
    } else {
      onInit();
    }
  }, []);

  const onInit = (cb) => {
    showLoading({ title: '操作中，请等待' });
    baseService
      .query('/api-getSessionID.json', {})
      .then(({ status, data }) => {
        if (status === 'success') {
          const { sessionName, sessionID } = data;
          setCache(CacheCookies, `${sessionName}=${sessionID}`);
          hideLoading();
          if (lastLoginUserName && lastLoginPassword) {
            setIsAuth(true);
          } else if (lastLoginUserName) {
            setFocus({ un: false, pw: true });
          } else {
            setFocus({ un: true, pw: false });
          }
        } else {
          console.error("ERR:",data);
          showToast({ title: 'sso登录失败', icon: 'none' });
        }
      })
      .catch(() => {
        showToast({ title: 'sso登录失败@Error', icon: 'none' });
        hideLoading();
      });
  };

  const onLogin = (cup = null) => {
    cup = cup || up;
    if (Object.keys(cup).length !== 2) {
      showToast({ title: '请输入账号密码信息', icon: 'none' });
      return;
    }
    showLoading({ title: '操作中' });
    login();
    baseService
      .query('/user-login.json', cup)
      .then(({ status, user, message }) => {
        if (status === 'success') {
          console.log(user);
          setCache(CacheUserInfo, user);
          setCache(CacheLastLoginUserName, cup['account']);
          setCache(CacheLastLoginPassword, cup['password']);
          setCache(CacheLastLoginDate, dayjs().format('YYYY/MM/DD HH:mm:ss'));
          showToast({ title: '登录成功' });
          onLoginSuccess();
        } else {
          showToast({ title: '登录失败', icon: 'none' });
        }
      })
      .catch(() => {
        showToast({ title: '登录失败@Error', icon: 'none' });
        hideLoading();
      });
  };

  const onLoginSuccess = () => {
    if (ref) {
      if (ref.includes('auth/login')) {
        redirectHomePage();
      } else {
        try {
          redirectTo({
            url: ref
          });
        } catch (error) {
          console.error(error);
          switchTab({ url: ref });
        }
      }
    } else {
      redirectHomePage();
    }
  };

  const redirectHomePage = () => {
    const { role } = getCache(CacheUserInfo) || {};
    switchTab({ url: role === 'dev' ? '/pages/rd/index' : '/pages/workb/index' });
  };

  const onChange = (key, e) => {
    const value = e.detail.value;
    setUp({ ...up, [key]: value.trim() });
    return value;
  };

  const onEnterApp = () => {
    setShowAdLayout(false);
  };

  const onBioAuth = (status, message) => {
    setIsAuth(false);
    if (status === 1) {
      onLogin({
        account: lastLoginUserName,
        password: lastLoginPassword
      });
    } else {
      showToast({ title: '生物认证失败', icon: 'none' });
    }
  };

  return (
    <Layout isShowHeader={true}>
      <BioCore isAuth={isAuth} onAuth={onBioAuth}></BioCore>
      <XList isCustomize={true}>
        <XInput
          label="账号"
          placeholder="禅道账号"
          value={up['account']}
          focus={focus.un}
          onChange={onChange.bind(this, 'account')}
        ></XInput>
      </XList>
      <XList isCustomize={true}>
        <XInput
          type="password"
          label="密码"
          placeholder="密码"
          focus={focus.pw}
          onChange={onChange.bind(this, 'password')}
        ></XInput>
      </XList>
      <XList isCustomize={true} style={{ background: '#e8e8e8', fontSize: '12px', color: '#999' }}>
        <View style={{ textAlign: 'center' }}>
          请使用禅道系统账号密码登录，可在小程序中直接进行bug管理
        </View>
      </XList>
      <XList isCustomize={true} style={{ marginTop: '30px' }} onClick={onLogin.bind(this, null)}>
        <View style={{ textAlign: 'center' }}>登录系统</View>
      </XList>
      <View
        style={{
          display: 'flex',
          flexDirection: 'column',
          fontSize: '12px',
          color: '#aaa',
          position: 'absolute',
          bottom: '10px',
          width: '100%'
        }}
      >
        <Text style={{ textAlign: 'center' }}>xiaox-zentao</Text>
        <Text style={{ textAlign: 'center' }}>
          Copyright @ 2007-{dayjs().get('year')} 
        </Text>
      </View>
    </Layout>
  );
};

Login.config = { navigationStyle: 'custom' };

export default Login;
